package com.qianguo.shop.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.eva.androidlibrary.widget.CircleImageView;
import com.eva.androidlibrary.widget.mdedittext.MaterialEditText;
import com.qianguo.shop.R;
import com.qianguo.shop.base.App;
import com.qianguo.shop.base.BaseTitleActivity;
import com.qianguo.shop.entity.Message;
import com.qianguo.shop.entity.MessageList;
import com.qianguo.shop.entity.mock.MockMessageList;
import com.qianguo.shop.widget.ResizableLinearLayout;
import com.eva.androidlibrary.widget.SwipeRefreshRecyclerView;

import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

/**
 * @author eva
 * @date 15/11/29
 */

@EActivity(R.layout.activity_im_message_list)
public class IMMessageActivity extends BaseTitleActivity {

    private static final int VIEW_TYPE_MY_MESSAGE = 2;
    private static final int VIEW_TYPE_OTHER_MESSAGE = 3;

    @ViewById(R.id.im_message_root)
    ResizableLinearLayout mRoot;
    @ViewById(R.id.im_message_list)
    SwipeRefreshRecyclerView mRcvMessageList;
    @ViewById(R.id.input_method_panel)
    FrameLayout mFmlInputMethodPanel;
    @ViewById(R.id.btn_input_method_switcher)
    ImageView mBtnInputMethodSwitcher;
    @ViewById(R.id.btn_insert_emoticon)
    ImageView mBtnInsertEmoticon;
    @ViewById(R.id.btn_insert_media)
    ImageView mBtnInsertMedia;
    @ViewById(R.id.message_input)
    MaterialEditText mEdtMessageInput;

    private boolean mInputMethodIsKeyboardMode = true;

    private MessageAdapter mAdapter = null;
    private MessageList mMessageList = null;
    private int mMyId = -1;
    private int mContactId = -1;
    private String mUsername = null;

    private InputMethodManager mInputMethodManager = null;
    private int mInputMethodHeight = -1;

    public static void jumpToIMMessageActivity(@NonNull Context context, int contactId, int myUserId) {
        jumpToIMMessageActivity(context, contactId, myUserId, null);
    }

    public static void jumpToIMMessageActivity(@NonNull Context context, int contactId, int myUserId, String username) {
        Intent intent = new Intent(context, IMMessageActivity_.class);
        intent.putExtra("user_id", myUserId)
                .putExtra("contact", contactId);
        if (username != null) {
            intent.putExtra("username", username);
        }
        context.startActivity(intent);
    }

    @Override
    protected String getToolbarTitle() {
        return "消息";
    }

    @Override
    protected void initializeUI() {
        mAdapter = new MessageAdapter(this);
        mRcvMessageList.setAdapter(mAdapter);

        mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        final Intent intent = getIntent();
        mMyId = intent.getIntExtra("user_id", -1);
        mContactId = intent.getIntExtra("contact", -1);
        if (intent.hasExtra("username")) {
            mUsername = intent.getStringExtra("username");
            setToolBarTitle(mUsername);
        }
        mMessageList = new MockMessageList(mContactId);
        mAdapter.notifyDataSetChanged();

        mRoot.setOnSizeChangedListener(new ResizableLinearLayout.OnSizeChangedListener() {
            @Override
            public void onSizeChanged(int w, int h, int oldw, int oldh, int dw, final int dh) {
                mInputMethodHeight = Math.abs(dh);
                if (dh > 0) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            ViewGroup.LayoutParams lp = mFmlInputMethodPanel.getLayoutParams();
                            if (mInputMethodIsKeyboardMode) {
                                lp.height = dh;
                            } else {
                                lp.height = 0;
                            }
                            mFmlInputMethodPanel.setLayoutParams(lp);
                        }
                    });

                } else {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            ViewGroup.LayoutParams lp = mFmlInputMethodPanel.getLayoutParams();
                            lp.height = 0;
                            mFmlInputMethodPanel.setLayoutParams(lp);
                        }
                    });
                }
            }
        });
    }

    @Click(R.id.btn_input_method_switcher)
    public void onInputMethodSwitcherClick(View v) {
        if (mInputMethodIsKeyboardMode) {
            if (mInputMethodManager.isActive(mEdtMessageInput)) {
                mInputMethodManager.hideSoftInputFromWindow(mEdtMessageInput.getWindowToken(), 0);
            } else {
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        ViewGroup.LayoutParams lp = mFmlInputMethodPanel.getLayoutParams();
                        lp.height = 0;
                        mFmlInputMethodPanel.setLayoutParams(lp);
                    }
                });
            }
            ((ImageView) v).setImageDrawable(getResources().getDrawable(R.drawable.ic_settings_voice_black));
        } else {
            if (!mEdtMessageInput.isFocused()) {
                mEdtMessageInput.requestFocus();
            }
            mInputMethodManager.showSoftInput(mEdtMessageInput, 0);

            ((ImageView) v).setImageDrawable(getResources().getDrawable(R.drawable.ic_keyboard_black));
        }
        mInputMethodIsKeyboardMode = !mInputMethodIsKeyboardMode;
    }

    @Click(R.id.btn_insert_media)
    public void onInsertMediaButtonClick(View v) {
        if (mInputMethodManager.isActive(mEdtMessageInput)) {
            mInputMethodManager.hideSoftInputFromWindow(mEdtMessageInput.getWindowToken(), 0);
        } else {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    ViewGroup.LayoutParams lp = mFmlInputMethodPanel.getLayoutParams();
                    lp.height = mInputMethodHeight;
                    mFmlInputMethodPanel.setLayoutParams(lp);
                }
            });
        }
    }

    private class MessageAdapter extends RecyclerView.Adapter<MessageViewHolder> {

        private Context mContext = null;
        private LayoutInflater mInflater = null;

        MessageAdapter(Context context) {
            mContext = context;
            mInflater = LayoutInflater.from(context);
        }

        @Override
        public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (VIEW_TYPE_MY_MESSAGE == viewType) {
                return new MyMessageViewHolder(mInflater.inflate(R.layout.item_message_my, parent, false));
            } else {
                return new OtherMessageViewHolder(mInflater.inflate(R.layout.item_message_other, parent, false));
            }
        }

        @Override
        public void onBindViewHolder(MessageViewHolder holder, int position) {
            holder.onBind(getItemAt(position));
        }

        Message getItemAt(int position) {
            return mMessageList.getItemAt(position);
        }

        @Override
        public int getItemCount() {
            return mMessageList.getItemCount();
        }

        @Override
        public int getItemViewType(int position) {
            if (getItemAt(position).getUserId() == mMyId) {
                return VIEW_TYPE_MY_MESSAGE;
            } else {
                return VIEW_TYPE_OTHER_MESSAGE;
            }
        }
    }

    private static class MessageViewHolder extends RecyclerView.ViewHolder {

        TextView txvMessage;
        CircleImageView txvAvatar;
        private App mApp = null;
        private Message mMessage = null;

        public MessageViewHolder(View itemView) {
            super(itemView);
            final Context ctx = itemView.getContext().getApplicationContext();
            if (ctx instanceof App) {
                mApp = (App) ctx;
            }
            txvMessage = (TextView) itemView.findViewById(R.id.im_message);
            txvAvatar = (CircleImageView) itemView.findViewById(R.id.im_avater);
        }

        public void onBind(Message message) {
            mMessage = message;
            txvMessage.setText(mMessage.getContent());
            if (mApp != null) {
                mApp.getGlobalImageLoader().loadImage(mApp, txvAvatar, mMessage.getAvatarUrl());
            }
        }
    }

    private static class MyMessageViewHolder extends MessageViewHolder {

        public MyMessageViewHolder(View itemView) {
            super(itemView);
        }
    }

    private static class OtherMessageViewHolder extends MessageViewHolder {

        public OtherMessageViewHolder(View itemView) {
            super(itemView);
        }
    }
}
